<?php
defined('BASEPATH') or exit('No direct script access allowed');

class LogManage extends MY_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->library('CreateExcel');
        $this->load->model('ChatRecord');
    }

    public function index()
    {
        $this->recordOfNotResolved();
    }

    /* 显示未解决问题页面 */
    public function recordOfNotResolved()
    {
        $category = file_get_contents(INTERFACE_RECORD_CATEGORY);
        $data['category'] = json_decode($category, true);
        $this->load->view('logManage/recordOfNotResolved', $data);
    }

    /* 获取未解决问题列表 */
    public function recordOfNotResolvedOpt()
    {
        $data = array(
            'code' => 0,
            'msg' => ''
        );
        $currentPage = isset($_REQUEST['currentPage']) ? $_REQUEST['currentPage'] : '';
        $showNumber = isset($_REQUEST['showNumber']) ? $_REQUEST['showNumber'] : '';
        $categoryContent = json_decode(file_get_contents(INTERFACE_RECORD_CATEGORY), true); // 获取分类
        $categoryCount = count($categoryContent);
        $res = $this->SetNotResolvedCondition($_REQUEST);
        $condition = $res['condition'];
        $limit = $res['limit'];
        $like = $res['like'];
        $result = $this->ChatRecord->find($condition, array(
            '*'
        ), 'id asc', $limit, $like);
        if (empty($result)) {
            $data['msg'] = '未查询到数据!';
            echo json_encode($data);
            return false;
        }
        $dataOfReturn = array(); // 返回的数据
        $SerialNumber = 1; // 序号
        foreach ($result as $k => $v) {
            $tmp['recordid'] = $v['id'];
            $tmp['SerialNumber'] = $SerialNumber ++;
            $tmp['userid'] = $v['sender'];
            $tmp['username'] = $v['sender_name'];
            $tmp['question'] = htmlspecialchars($v['comment']);
            $tmp['answer'] = htmlspecialchars($v['bind_answer']);
            $category = $v['category'];
            if (empty($category) || $category >= $categoryCount) {
                $category = 10;
            }
            $tmp['category'] = $categoryContent[$category];
            $tmp['time'] = date('Y-m-d H:i:s', $v['ctime']);
            $tmp['add'] = $v['is_add'];
            $tmp['ignore'] = $v['is_ignore'];
            $dataOfReturn[] = $tmp;
        }
        $result = $this->ChatRecord->find($condition, array(
            'id'
        ), 'id asc', array(), $like);
        $count = count($result);
        $pageSet = array(
            'totalPage' => ceil($count / $showNumber),
            'showPage' => PAGE_NUMBER,
            'pageNumber' => (int) $currentPage,
            'totalCount' => $count,
            'showNumber' => (int) $showNumber
        );
        $data['code'] = 1;
        $data['msg'] = '查询成功！';
        $data['res'] = $dataOfReturn;
        $data['page'] = $pageSet;
        echo json_encode($data);
    }

    /* 未解决问题生成excel表格 */
    public function getExcelOfRecord($param)
    {
        /* 解析参数 */
        $categoryContent = json_decode(file_get_contents(INTERFACE_RECORD_CATEGORY), true); // 获取分类
        $param = urldecode($param);
        $param = json_decode($param, true);
        $res = $this->SetNotResolvedCondition($param);
        $condition = $res['condition'];
        $like = $res['like'];
        $limit = array();
        $result = $this->ChatRecord->find($condition, array(
            '*'
        ), 'id asc', $limit, $like);
        $excelTitle = array(
            '序号',
            '用户ID',
            '用户名',
            '用户问题',
            '机器人回复',
            '渠道来源',
            '提问时间'
        );
        $excelContent = array();
        
        /* 获取查询到的数据 */
        if ($result) {
            $SerialNumber = 1; // 序号
            foreach ($result as $k => $v) {
                $category = isset($v['category']) ? $v['category'] : 10;
                $excelContent[] = array(
                    $SerialNumber ++,
                    $v['sender'],
                    $v['sender_name'],
                    $v['comment'],
                    $v['bind_answer'],
                    isset($categoryContent[$category]) ? $categoryContent[$category] : '未知',
                    date('Y-m-d H:i:s', $v['ctime'])
                );
            }
        }
        $this->createexcel->setProperties($excelTitle, $excelContent);
        $this->createexcel->getExcel('explorer');
    }

    /* 记录中的操作项 */
    public function operate()
    {
        $data = array(
            'code' => 0,
            'msg' => ''
        );
        $id = $_REQUEST['recordid'];
        $k = $_REQUEST['type'];
        $v = $_REQUEST['value'];
        $condition = array(
            'id' => $id
        );
        $value = array(
            $k => $v
        );
        $result = $this->ChatRecord->update($condition, $value);
        if ($result) {
            $data['code'] = 1;
            $data['msg'] = '操作成功！';
        } else {
            $data['msg'] = '操作失败！';
        }
        echo json_encode($data);
    }

    /* 查看历史记录 */
    public function showHistory($userid)
    {
        $date = date('Y-m-d');
        $data = array(
            'code' => 0,
            'date' => $date
        );
        $condition = "sender=$userid or receiver=$userid";
        $result = $this->ChatRecord->find($condition);
        if (! empty($result)) {
            $data['code'] = 1;
            foreach ($result as $k => $v) {
                if ($userid == $v['sender']) {
                    $username = $v['sender_name'];
                }
                $senderName = $v['sender_name'];
                if (WEBCHAT_ROBOT_ID == $senderName) {
                    $tmp['username'] = '同花顺智能机器人';
                } else 
                    if (empty($senderName)) {
                        $tmp['username'] = '未知用户';
                    } else {
                        $tmp['username'] = $senderName;
                    }
                $tmp['time'] = date('Y-m-d H:i:s', $v['ctime']);
                $tmp['message'] = $v['comment'];
                $info[] = $tmp;
            }
            $data['username'] = $username;
            $data['res'] = json_encode($info);
        }
        $this->load->view('logManage/showHistory', $data);
    }

    /* 显示自动问答界面 */
    public function autoQA()
    {
        $data = array();
        $platform = json_decode(file_get_contents(QUESTION_PLATFORM), true);
        $category = json_decode(file_get_contents(INTERFACE_RECORD_CATEGORY), true);
        $data['platform'] = $platform;
        $data['category'] = $category;
        $this->load->view('logManage/autoQA', $data);
    }

    /* 查询自动问答记录 */
    public function getAutoQA()
    {
        /* 参数初始化 */
        $data = array(
            'code' => 0,
            'msg' => ''
        );
        $currentPage = $_REQUEST['currentPage'];
        $showNumber = $_REQUEST['showNumber'];
        $categoryContent = json_decode(file_get_contents(INTERFACE_RECORD_CATEGORY, true)); // 获取分类
        $categoryCount = count($categoryContent);
        $res = $this->setAutoQACondition($_REQUEST);
        $conditon = $res['condition'];
        $limit = $res['limit'];
        $like = $res['like'];
        $result = $this->ChatRecord->find($conditon, array(
            '*'
        ), 'id asc', $limit, $like);
        if (empty($result)) {
            $data['msg'] = '未查询到数据!';
            echo json_encode($data);
            return false;
        }
        $dataOfReturn = array(); // 返回的数据
        $SerialNumber = 1; // 序号
        foreach ($result as $k => $v) {
            $tmp['recordid'] = $v['id'];
            $tmp['SerialNumber'] = $SerialNumber ++;
            $tmp['userid'] = $v['sender'];
            $tmp['username'] = $v['sender_name'];
            $tmp['question'] = htmlspecialchars($v['comment']);
            $tmp['answer'] = htmlspecialchars($v['bind_answer']);
            $tmp['standardAnswer'] = $v['question_type'];
            $tmp['time'] = date('Y-m-d H:i:s', $v['ctime']);
            $category = $v['category'];
            if (empty($category) || $category >= $categoryCount) {
                $category = 10;
            }
            $tmp['category'] = $categoryContent[$category];
            $tmp['platform'] = $v['platform'];
            $dataOfReturn[] = $tmp;
        }
        $result = $this->ChatRecord->find($conditon, array(
            'id'
        ), 'id asc', array(), $like);
        $count = count($result);
        $pageSet = array(
            'totalPage' => ceil($count / $showNumber),
            'showPage' => PAGE_NUMBER,
            'pageNumber' => (int) $currentPage,
            'totalCount' => $count,
            'showNumber' => (int) $showNumber
        );
        $data['code'] = 1;
        $data['msg'] = '查询成功！';
        $data['res'] = $dataOfReturn;
        $data['page'] = $pageSet;
        echo json_encode($data);
    }

    /* 导出自动问答 */
    function exportAutoQA($param)
    {
        $param = urldecode($param);
        $param = json_decode($param, true);
        $res = $this->setAutoQACondition($param);
        $result = $this->ChatRecord->find($res['condition'], array(
            '*'
        ), 'id asc', array(), $res['like']);
        
        $categoryContent = json_decode(file_get_contents(INTERFACE_RECORD_CATEGORY, true)); // 获取分类
        /* 生成excel表格 */
        $excelContent = array();
        $excelTitle = array(
            '序号',
            '用户ID',
            '用户名',
            '用户问题',
            '标准问题',
            '机器回复',
            '提问时间',
            '提问来源',
            '系统平台'
        );
        if ($result) {
            $SerialNumber = 1; // 序号
            foreach ($result as $k => $v) {
                $category = isset($v['category']) ? $v['category'] : 10;
                $excelContent[] = array(
                    $SerialNumber ++,
                    $v['sender'],
                    $v['sender_name'],
                    $v['comment'],
                    $v['question_type'],
                    $v['bind_answer'],
                    date('Y-m-d H:i:s', $v['ctime']),
                    isset($categoryContent[$category]) ? $categoryContent[$category] : '未知',
                    $v['platform']
                );
            }
        }
        $this->createexcel->setProperties($excelTitle, $excelContent);
        $this->createexcel->getExcel('explorer');
    }

    /* 自动问答条件设置 */
    private function setAutoQACondition($param)
    {
        /* 参数初始化 */
        $data = array();
        $startTime = $param['startTime'];
        $endTime = $param['endTime'];
        $userid = trim($param['userid']);
        $questionType = $param['questionType'];
        $keyword = trim($param['keyword']);
        $category = $param['questionFrom'];
        $platform = $param['platform'];
        $currentPage = $param['currentPage'];
        $showNumber = $param['showNumber'];
        
        $startTime = strtotime($startTime);
        $endTime = strtotime($endTime);
        $endTime += 3600 * 24;
        $platformContent = json_decode(file_get_contents(QUESTION_PLATFORM), true); // 获取系统
        $platform = $platformContent[$platform];
        
        /* 添加查询条件 */
        $conditon = array(
            'ctime >= ' => $startTime,
            'ctime < ' => $endTime,
            'question_type != ' => '搜索类',
            'question_type <> ' => '问题无法回复',
            'from_type ' => 2,
            'receiver' => WEBCHAT_ROBOT_ID
        );
        if (! empty($userid)) {
            $conditon['sender_name'] = $userid;
        }
        if (0 != (int) $category) {
            $conditon['category'] = $category;
        }
        if ('全部' != $platform) {
            $conditon['platform'] = $platform;
        }
        $limit = array(
            'number' => $showNumber,
            'start' => ($currentPage - 1) * $showNumber
        );
        $like = array();
        if (! empty($keyword)) {
            switch ((int) $questionType) {
                case 1:
                    $like['comment'] = $keyword;
                    break;
                case 2:
                    $like['question_type'] = $keyword;
                    break;
                case 3:
                    $like['bind_answer'] = $keyword;
                    break;
                default:
                    break;
            }
        }
        
        $data = array(
            'condition' => $conditon,
            'limit' => $limit,
            'like' => $like
        );
        return $data;
    }

    /* 未解决问题条件设置 */
    private function SetNotResolvedCondition($param)
    {
        $startTime = isset($param['startTime']) ? $param['startTime'] : '';
        $endTime = isset($param['endTime']) ? $param['endTime'] : '';
        $category = isset($param['source']) ? $param['source'] : '';
        $keyword = isset($param['keyword']) ? $param['keyword'] : '';
        $username = isset($param['username']) ? $param['username'] : '';
        $operate = isset($param['operate']) ? $param['operate'] : '';
        $currentPage = isset($param['currentPage']) ? $param['currentPage'] : '';
        $showNumber = isset($param['showNumber']) ? $param['showNumber'] : '';
        
        /* 时间转换 */
        $startTime = strtotime($startTime);
        $endTime = strtotime($endTime);
        $endTime += 3600 * 24;
        
        /* 添加查询条件 */
        $conditon = "(question_type = '问题无法回复' or question_type = '搜索类') and ctime >= $startTime and ctime< $endTime ";
        if (! empty($username)) {
            $conditon .= "and sender_name = '$username' ";
        }
        if (0 != (int) $category) {
            $conditon .= "and category = $category ";
        }
        switch ((int) $operate) {
            case 1:
                break;
            case 2:
                $conditon .= "and is_add = 0 and is_ignore = 0 ";
                break;
            case 3:
                $conditon .= "and is_add = 1 ";
                break;
            case 4:
                $conditon .= "and is_ignore = 1 ";
                break;
            default:
                break;
        }
        $limit = array(
            'number' => $showNumber,
            'start' => ($currentPage - 1) * $showNumber
        );
        $like = array();
        if (! empty($keyword)) {
            $like['comment'] = $keyword;
        }
        $data = array(
            'condition' => $conditon,
            'limit' => $limit,
            'like' => $like
        );
        return $data;
    }
}